<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import {
  UserAddOutlined,
  TeamOutlined,
  ReloadOutlined,
  EyeOutlined,
  EditOutlined,
  SearchOutlined,
  WalletOutlined,
  DownloadOutlined,
} from '@ant-design/icons-vue'
import { useWallet } from '../../../composables/useWallet'

const {
  isConnected,
  isReady,
  currentAccount,
} = useWallet()

// 家族列表
const familyList = ref<any[]>([])
const selectedFamilyId = ref('')
const isLoadingFamilies = ref(false)

// 成员列表
const memberList = ref<any[]>([])
const isLoadingMembers = ref(false)

// 搜索和筛选
const searchKeyword = ref('')
const filterGeneration = ref('')
const filterStatus = ref('')

// 模态框
const addMemberModalVisible = ref(false)
const memberDetailModalVisible = ref(false)
const editMemberModalVisible = ref(false)

// 选中的成员
const selectedMember = ref<any>(null)

// 添加成员表单
const addMemberForm = ref({
  memberAddress: '',
  name: '',
  role: 'member',
  generation: 1,
  birthYear: new Date().getFullYear() - 30,
  deathYear: 0,
  parent: '',
  metadataURI: ''
})

// 钱包生成模式
const useGeneratedWallet = ref(false)
const generatedWallet = ref<any>(null)

// 编辑成员表单
const editMemberForm = ref({
  wallet: '',
  name: '',
  role: '',
  generation: 0,
  birthYear: 0,
  deathYear: 0,
  parent: '',
  metadataURI: ''
})

const isAddingMember = ref(false)
const isUpdatingMember = ref(false)

/**
 * 生成钱包
 */
async function generateWallet() {
  try {
    // 动态导入 ethers
    const { ethers } = await import('ethers')
    
    // 生成随机钱包
    const wallet = ethers.Wallet.createRandom()
    
    generatedWallet.value = {
      address: wallet.address,
      privateKey: wallet.privateKey,
      mnemonic: wallet.mnemonic?.phrase || ''
    }
    
    // 自动填入地址
    addMemberForm.value.memberAddress = wallet.address
    useGeneratedWallet.value = true
    
    message.success('钱包已生成！请务必保存私钥和助记词')
  } catch (error: any) {
    console.error('❌ 生成钱包失败:', error)
    message.error('生成钱包失败，请检查是否已安装 ethers 库')
  }
}

/**
 * 下载钱包信息
 */
function downloadWalletInfo() {
  if (!generatedWallet.value) return
  
  const walletInfo = {
    name: addMemberForm.value.name,
    address: generatedWallet.value.address,
    privateKey: generatedWallet.value.privateKey,
    mnemonic: generatedWallet.value.mnemonic,
    warning: '⚠️ 警告：私钥和助记词是恢复钱包的唯一凭证，请妥善保管，切勿泄露！',
    createdAt: new Date().toLocaleString('zh-CN')
  }
  
  const blob = new Blob([JSON.stringify(walletInfo, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `wallet-${addMemberForm.value.name || 'member'}-${Date.now()}.json`
  a.click()
  URL.revokeObjectURL(url)
  
  message.success('钱包信息已下载')
}

/**
 * 复制私钥
 */
function copyPrivateKey() {
  if (!generatedWallet.value) return
  
  navigator.clipboard.writeText(generatedWallet.value.privateKey)
  message.success('私钥已复制到剪贴板')
}

/**
 * 复制助记词
 */
function copyMnemonic() {
  if (!generatedWallet.value) return
  
  navigator.clipboard.writeText(generatedWallet.value.mnemonic)
  message.success('助记词已复制到剪贴板')
}

// 组件挂载时加载家族列表
onMounted(async () => {
  await loadFamilyList()
})

// 监听家族选择变化
watch(selectedFamilyId, (newId) => {
  if (newId) {
    loadFamilyMembers(newId)
  }
})

/**
 * 加载家族列表
 */
async function loadFamilyList() {
  isLoadingFamilies.value = true
  
  try {
    const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
    const response = await fetch(`${apiBaseUrl}/blockchain/family/list`)
    const result = await response.json()
    
    if (result.code === 200) {
      familyList.value = result.data || []
      
      // 如果只有一个家族，自动选中
      if (familyList.value.length === 1) {
        selectedFamilyId.value = familyList.value[0].id
      }
    }
  } catch (error: any) {
    console.error('❌ 加载家族列表失败:', error)
    message.error('加载家族列表失败')
  } finally {
    isLoadingFamilies.value = false
  }
}

/**
 * 加载家族成员
 */
async function loadFamilyMembers(familyId: string) {
  if (!familyId) return
  
  isLoadingMembers.value = true
  
  try {
    const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
    const response = await fetch(`${apiBaseUrl}/blockchain/family/${familyId}/members`)
    const result = await response.json()
    
    if (result.code === 200) {
      memberList.value = result.data || []
      console.log('✅ 成员列表加载完成:', memberList.value.length)
    }
  } catch (error: any) {
    console.error('❌ 加载成员列表失败:', error)
    message.error('加载成员列表失败')
  } finally {
    isLoadingMembers.value = false
  }
}

/**
 * 添加成员
 */
async function addMember() {
  if (!selectedFamilyId.value) {
    message.error('请先选择家族')
    return
  }
  
  if (!addMemberForm.value.memberAddress || !addMemberForm.value.name) {
    message.error('请填写成员地址和姓名')
    return
  }
  
  isAddingMember.value = true
  
  try {
    const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
    const response = await fetch(
      `${apiBaseUrl}/blockchain/family/${selectedFamilyId.value}/member`,
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          memberAddress: addMemberForm.value.memberAddress,
          name: addMemberForm.value.name,
          role: addMemberForm.value.role,
          generation: addMemberForm.value.generation,
          birthYear: addMemberForm.value.birthYear,
          deathYear: addMemberForm.value.deathYear,
          parent: addMemberForm.value.parent,
          metadataURI: addMemberForm.value.metadataURI
        })
      }
    )
    
    const result = await response.json()
    
    if (result.code === 200) {
      const txHash = result.data?.txHash
      message.success(`成员 "${addMemberForm.value.name}" 添加成功！交易Hash: ${txHash?.substring(0, 10)}...`)
      
      // 关闭模态框
      addMemberModalVisible.value = false
      
      // 重置表单
      addMemberForm.value = {
        memberAddress: '',
        name: '',
        role: 'member',
        generation: 1,
        birthYear: new Date().getFullYear() - 30,
        deathYear: 0,
        parent: '',
        metadataURI: ''
      }
      
      // 等待交易确认（区块链需要时间）
      message.loading('等待区块确认...', 2)
      await new Promise(resolve => setTimeout(resolve, 3000))
      
      // 刷新列表（多次尝试）
      console.log('📋 开始刷新成员列表...')
      for (let i = 0; i < 3; i++) {
        await loadFamilyMembers(selectedFamilyId.value)
        if (i < 2) {
          await new Promise(resolve => setTimeout(resolve, 1000))
        }
      }
      
      message.success('成员列表已更新')
    } else {
      throw new Error(result.message || '添加失败')
    }
  } catch (error: any) {
    console.error('❌ 添加成员失败:', error)
    message.error(`添加失败: ${error.message}`)
  } finally {
    isAddingMember.value = false
  }
}

/**
 * 查看成员详情
 */
function viewMemberDetail(member: any) {
  selectedMember.value = member
  memberDetailModalVisible.value = true
}

/**
 * 编辑成员
 */
function editMember(member: any) {
  editMemberForm.value = {
    wallet: member.wallet,
    name: member.name,
    role: member.role,
    generation: member.generation,
    birthYear: member.birthYear,
    deathYear: member.deathYear || 0,
    parent: member.parent || '',
    metadataURI: member.metadataURI || ''
  }
  editMemberModalVisible.value = true
}

/**
 * 更新成员信息
 */
async function updateMember() {
  if (!selectedFamilyId.value) return
  
  isUpdatingMember.value = true
  
  try {
    const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
    const response = await fetch(
      `${apiBaseUrl}/blockchain/family/${selectedFamilyId.value}/member/${editMemberForm.value.wallet}`,
      {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: editMemberForm.value.name,
          role: editMemberForm.value.role,
          generation: editMemberForm.value.generation,
          birthYear: editMemberForm.value.birthYear,
          deathYear: editMemberForm.value.deathYear,
          parent: editMemberForm.value.parent,
          metadataURI: editMemberForm.value.metadataURI
        })
      }
    )
    
    const result = await response.json()
    
    if (result.code === 200) {
      message.success('成员信息更新成功！')
      editMemberModalVisible.value = false
      await loadFamilyMembers(selectedFamilyId.value)
    } else {
      throw new Error(result.message || '更新失败')
    }
  } catch (error: any) {
    console.error('❌ 更新成员失败:', error)
    message.error(`更新失败: ${error.message}`)
  } finally {
    isUpdatingMember.value = false
  }
}

/**
 * 筛选后的成员列表
 */
const filteredMembers = computed(() => {
  let result = memberList.value
  
  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(m => 
      m.name?.toLowerCase().includes(keyword) ||
      m.wallet?.toLowerCase().includes(keyword)
    )
  }
  
  // 世代筛选
  if (filterGeneration.value !== '') {
    result = result.filter(m => m.generation === Number(filterGeneration.value))
  }
  
  // 状态筛选
  if (filterStatus.value === 'active') {
    result = result.filter(m => !m.deathYear || m.deathYear === 0)
  } else if (filterStatus.value === 'deceased') {
    result = result.filter(m => m.deathYear && m.deathYear > 0)
  }
  
  return result
})

/**
 * 成员统计
 */
const memberStats = computed(() => ({
  total: memberList.value.length,
  active: memberList.value.filter(m => !m.deathYear || m.deathYear === 0).length,
  deceased: memberList.value.filter(m => m.deathYear && m.deathYear > 0).length,
  generations: new Set(memberList.value.map(m => m.generation)).size
}))

/**
 * 工具函数
 */
function formatAddress(address: string) {
  if (!address) return '-'
  return `${address.slice(0, 6)}...${address.slice(-4)}`
}

function getGenerationColor(generation: number) {
  const colors = ['#f5222d', '#fa8c16', '#fadb14', '#52c41a', '#1890ff', '#722ed1']
  return colors[generation % colors.length]
}

function getRoleColor(role: string) {
  const colors: any = {
    patriarch: 'red',
    elder: 'orange',
    member: 'blue',
    youth: 'green'
  }
  return colors[role] || 'default'
}

function getRoleName(role: string) {
  if (!role || role.trim() === '') {
    return '—'
  }
  const names: any = {
    patriarch: '族长',
    elder: '长老',
    member: '成员',
    youth: '青年'
  }
  return names[role] || role
}

function calculateAge(birthYear: number, deathYear: number) {
  if (!birthYear) return '-'
  const endYear = deathYear || new Date().getFullYear()
  return endYear - birthYear
}

function formatTimestamp(timestamp: number) {
  if (!timestamp) return '-'
  return new Date(timestamp * 1000).toLocaleString('zh-CN')
}
</script>

<template>
  <div class="family-members-optimized">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h2><TeamOutlined /> 成员管理中心</h2>
        <p>管理家族成员信息，建立完整的家族档案</p>
      </div>
    </div>

    <!-- 家族选择和操作栏 -->
    <a-card style="margin-bottom: 16px">
      <a-space size="middle" style="width: 100%; justify-content: space-between">
        <a-space>
          <span style="font-weight: 500">选择家族:</span>
          <a-select
            v-model:value="selectedFamilyId"
            placeholder="请选择要管理的家族"
            style="width: 300px"
            :loading="isLoadingFamilies"
          >
            <a-select-option
              v-for="family in familyList"
              :key="family.id"
              :value="family.id"
            >
              {{ family.name }} (ID: {{ family.id }})
            </a-select-option>
          </a-select>
        </a-space>
        
        <a-space>
          <a-button
            type="primary"
            :disabled="!selectedFamilyId"
            @click="addMemberModalVisible = true"
          >
            <UserAddOutlined /> 添加成员
          </a-button>
          
          <a-button
            :disabled="!selectedFamilyId"
            :loading="isLoadingMembers"
            @click="loadFamilyMembers(selectedFamilyId)"
          >
            <ReloadOutlined /> 刷新
          </a-button>
        </a-space>
      </a-space>
    </a-card>

    <!-- 成员管理区域 -->
    <template v-if="selectedFamilyId">
      <!-- 搜索和筛选 -->
      <a-card style="margin-bottom: 16px">
        <a-space size="middle" wrap>
          <a-input-search
            v-model:value="searchKeyword"
            placeholder="搜索成员姓名或地址"
            style="width: 250px"
            allow-clear
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </a-input-search>
          
          <a-select
            v-model:value="filterGeneration"
            placeholder="筛选世代"
            style="width: 150px"
            allow-clear
          >
            <a-select-option value="">全部世代</a-select-option>
            <a-select-option value="0">族长</a-select-option>
            <a-select-option value="1">第一代</a-select-option>
            <a-select-option value="2">第二代</a-select-option>
            <a-select-option value="3">第三代</a-select-option>
            <a-select-option value="4">第四代</a-select-option>
          </a-select>
          
          <a-select
            v-model:value="filterStatus"
            placeholder="筛选状态"
            style="width: 150px"
            allow-clear
          >
            <a-select-option value="">全部状态</a-select-option>
            <a-select-option value="active">在世</a-select-option>
            <a-select-option value="deceased">已故</a-select-option>
          </a-select>
        </a-space>
      </a-card>

      <!-- 成员统计 -->
      <a-row :gutter="16" style="margin-bottom: 16px">
        <a-col :xs="12" :sm="6">
          <a-card>
            <a-statistic
              title="总人数"
              :value="memberStats.total"
              :value-style="{ color: '#1890ff' }"
            >
              <template #prefix>
                <TeamOutlined />
              </template>
            </a-statistic>
          </a-card>
        </a-col>
        
        <a-col :xs="12" :sm="6">
          <a-card>
            <a-statistic
              title="在世"
              :value="memberStats.active"
              :value-style="{ color: '#52c41a' }"
            />
          </a-card>
        </a-col>
        
        <a-col :xs="12" :sm="6">
          <a-card>
            <a-statistic
              title="已故"
              :value="memberStats.deceased"
              :value-style="{ color: '#8c8c8c' }"
            />
          </a-card>
        </a-col>
        
        <a-col :xs="12" :sm="6">
          <a-card>
            <a-statistic
              title="世代数"
              :value="memberStats.generations"
              :value-style="{ color: '#722ed1' }"
            />
          </a-card>
        </a-col>
      </a-row>

      <!-- 成员列表 -->
      <a-card title="成员列表">
        <a-spin :spinning="isLoadingMembers" tip="加载中...">
          <a-empty v-if="filteredMembers.length === 0" description="暂无成员数据">
            <a-button type="primary" @click="addMemberModalVisible = true">
              <UserAddOutlined /> 添加第一个成员
            </a-button>
          </a-empty>

          <a-list
            v-else
            :data-source="filteredMembers"
            :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 4, xxl: 6 }"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <a-card hoverable class="member-card">
                  <template #title>
                    <div style="display: flex; align-items: center; gap: 8px">
                      <a-avatar :style="{ backgroundColor: getGenerationColor(item.generation) }">
                        {{ item.name?.charAt(0) || '?' }}
                      </a-avatar>
                      <span>{{ item.name || '未知' }}</span>
                      <a-tag v-if="item.deathYear > 0" color="gray" size="small">已故</a-tag>
                    </div>
                  </template>
                  
                  <a-descriptions :column="1" size="small">
                    <a-descriptions-item label="世代">
                      第 {{ item.generation }} 代
                    </a-descriptions-item>
                    
                    <a-descriptions-item label="出生">
                      {{ item.birthYear }} 年
                    </a-descriptions-item>
                    
                    <a-descriptions-item v-if="item.deathYear > 0" label="逝世">
                      {{ item.deathYear }} 年
                    </a-descriptions-item>
                    
                    <a-descriptions-item label="角色">
                      <a-tag :color="getRoleColor(item.role)" size="small">
                        {{ getRoleName(item.role) }}
                      </a-tag>
                    </a-descriptions-item>
                    
                    <a-descriptions-item label="地址">
                      <a-typography-text copyable style="font-size: 11px">
                        {{ formatAddress(item.wallet) }}
                      </a-typography-text>
                    </a-descriptions-item>
                  </a-descriptions>
                  
                  <div style="margin-top: 12px; display: flex; gap: 8px">
                    <a-button size="small" block @click="viewMemberDetail(item)">
                      <EyeOutlined /> 详情
                    </a-button>
                    <a-button size="small" block @click="editMember(item)">
                      <EditOutlined /> 编辑
                    </a-button>
                  </div>
                </a-card>
              </a-list-item>
            </template>
          </a-list>
        </a-spin>
      </a-card>
    </template>

    <!-- 未选择家族提示 -->
    <a-empty v-else description="请先选择要管理的家族">
      <a-button type="primary" @click="loadFamilyList">
        <ReloadOutlined /> 刷新家族列表
      </a-button>
    </a-empty>

    <!-- 添加成员模态框 -->
    <a-modal
      v-model:open="addMemberModalVisible"
      title="添加家族成员"
      :confirm-loading="isAddingMember"
      @ok="addMember"
      width="800px"
    >
      <a-form :model="addMemberForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="24">
            <a-alert
              v-if="!useGeneratedWallet"
              type="info"
              message="💡 提示"
              description="如果成员没有钱包，可以点击下方按钮自动生成一个新钱包"
              show-icon
              style="margin-bottom: 16px"
            />
            
            <a-alert
              v-else
              type="success"
              message="✅ 钱包已生成"
              description="请务必保存下方的私钥和助记词，这是恢复钱包的唯一凭证！"
              show-icon
              style="margin-bottom: 16px"
            />
          </a-col>
          
          <a-col :span="24">
            <a-form-item
              label="成员钱包地址"
              required
            >
              <a-input-group compact>
                <a-input
                  v-model:value="addMemberForm.memberAddress"
                  placeholder="0x... 或点击右侧按钮生成新钱包"
                  size="large"
                  style="width: calc(100% - 120px)"
                  :disabled="useGeneratedWallet"
                />
                <a-button
                  v-if="!useGeneratedWallet"
                  type="primary"
                  size="large"
                  @click="generateWallet"
                  style="width: 120px"
                >
                  <WalletOutlined /> 生成钱包
                </a-button>
                <a-button
                  v-else
                  danger
                  size="large"
                  @click="useGeneratedWallet = false; generatedWallet = null; addMemberForm.memberAddress = ''"
                  style="width: 120px"
                >
                  重新输入
                </a-button>
              </a-input-group>
            </a-form-item>
          </a-col>
          
          <!-- 生成的钱包信息 -->
          <a-col v-if="useGeneratedWallet && generatedWallet" :span="24">
            <a-card
              title="🔐 生成的钱包信息（请务必保存）"
              size="small"
              style="margin-bottom: 16px; background: #fff7e6; border-color: #ffa940"
            >
              <a-descriptions :column="1" size="small" bordered>
                <a-descriptions-item label="钱包地址">
                  <a-typography-text copyable>
                    {{ generatedWallet.address }}
                  </a-typography-text>
                </a-descriptions-item>
                
                <a-descriptions-item label="私钥">
                  <a-input-password
                    :value="generatedWallet.privateKey"
                    readonly
                    size="small"
                  />
                  <a-button size="small" type="link" @click="copyPrivateKey">
                    复制私钥
                  </a-button>
                </a-descriptions-item>
                
                <a-descriptions-item label="助记词">
                  <a-typography-paragraph copyable style="margin: 0; word-break: break-all">
                    {{ generatedWallet.mnemonic }}
                  </a-typography-paragraph>
                </a-descriptions-item>
              </a-descriptions>
              
              <a-button
                type="primary"
                block
                @click="downloadWalletInfo"
                style="margin-top: 12px"
              >
                <DownloadOutlined /> 下载钱包文件
              </a-button>
            </a-card>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="姓名" required>
              <a-input
                v-model:value="addMemberForm.name"
                placeholder="请输入姓名"
                size="large"
              />
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="角色">
              <a-select
                v-model:value="addMemberForm.role"
                size="large"
              >
                <a-select-option value="patriarch">族长</a-select-option>
                <a-select-option value="elder">长老</a-select-option>
                <a-select-option value="member">成员</a-select-option>
                <a-select-option value="youth">青年</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="世代" help="0-族长，1-第一代，2-第二代...">
              <a-input-number
                v-model:value="addMemberForm.generation"
                :min="0"
                :max="10"
                style="width: 100%"
                size="large"
              />
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="出生年份">
              <a-input-number
                v-model:value="addMemberForm.birthYear"
                :min="1900"
                :max="new Date().getFullYear()"
                style="width: 100%"
                size="large"
              />
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="逝世年份" help="在世成员填 0">
              <a-input-number
                v-model:value="addMemberForm.deathYear"
                :min="0"
                :max="new Date().getFullYear()"
                style="width: 100%"
                size="large"
              />
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="父母地址（可选）">
              <a-input
                v-model:value="addMemberForm.parent"
                placeholder="父母的钱包地址"
                size="large"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <!-- 成员详情模态框 -->
    <a-modal
      v-model:open="memberDetailModalVisible"
      :title="`成员详情 - ${selectedMember?.name || '未知'}`"
      :footer="null"
      width="800px"
    >
      <div v-if="selectedMember">
        <a-descriptions bordered :column="2">
          <a-descriptions-item label="姓名" :span="2">
            {{ selectedMember.name || '未知' }}
          </a-descriptions-item>
          
          <a-descriptions-item label="钱包地址" :span="2">
            <a-typography-text copyable>
              {{ selectedMember.wallet }}
            </a-typography-text>
          </a-descriptions-item>
          
          <a-descriptions-item label="世代">
            第 {{ selectedMember.generation }} 代
          </a-descriptions-item>
          
          <a-descriptions-item label="角色">
            <a-tag :color="getRoleColor(selectedMember.role)">
              {{ getRoleName(selectedMember.role) }}
            </a-tag>
          </a-descriptions-item>
          
          <a-descriptions-item label="出生年份">
            {{ selectedMember.birthYear }} 年
          </a-descriptions-item>
          
          <a-descriptions-item label="年龄">
            {{ calculateAge(selectedMember.birthYear, selectedMember.deathYear) }} 岁
          </a-descriptions-item>
          
          <a-descriptions-item v-if="selectedMember.deathYear > 0" label="逝世年份" :span="2">
            {{ selectedMember.deathYear }} 年
          </a-descriptions-item>
          
          <a-descriptions-item v-if="selectedMember.parent" label="父母" :span="2">
            <a-typography-text copyable>
              {{ selectedMember.parent }}
            </a-typography-text>
          </a-descriptions-item>
          
          <a-descriptions-item label="加入时间" :span="2">
            {{ formatTimestamp(selectedMember.joinedAt) }}
          </a-descriptions-item>
        </a-descriptions>
        
        <div style="margin-top: 24px; text-align: right">
          <a-space>
            <a-button @click="memberDetailModalVisible = false">
              关闭
            </a-button>
            <a-button type="primary" @click="editMember(selectedMember)">
              <EditOutlined /> 编辑信息
            </a-button>
          </a-space>
        </div>
      </div>
    </a-modal>

    <!-- 编辑成员模态框 -->
    <a-modal
      v-model:open="editMemberModalVisible"
      title="编辑成员信息"
      :confirm-loading="isUpdatingMember"
      @ok="updateMember"
      width="700px"
    >
      <a-form :model="editMemberForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="姓名">
              <a-input
                v-model:value="editMemberForm.name"
                size="large"
              />
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="角色">
              <a-select
                v-model:value="editMemberForm.role"
                size="large"
              >
                <a-select-option value="patriarch">族长</a-select-option>
                <a-select-option value="elder">长老</a-select-option>
                <a-select-option value="member">成员</a-select-option>
                <a-select-option value="youth">青年</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="世代">
              <a-input-number
                v-model:value="editMemberForm.generation"
                :min="0"
                :max="10"
                style="width: 100%"
                size="large"
              />
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="出生年份">
              <a-input-number
                v-model:value="editMemberForm.birthYear"
                :min="1900"
                :max="new Date().getFullYear()"
                style="width: 100%"
                size="large"
              />
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="逝世年份">
              <a-input-number
                v-model:value="editMemberForm.deathYear"
                :min="0"
                :max="new Date().getFullYear()"
                style="width: 100%"
                size="large"
              />
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="父母地址">
              <a-input
                v-model:value="editMemberForm.parent"
                size="large"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped lang="scss">
.family-members-optimized {
  .page-header {
    padding: 24px;
    margin-bottom: 24px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    color: white;
    
    .header-content {
      h2 {
        margin: 0 0 8px;
        font-size: 28px;
        color: white;
      }
      
      p {
        margin: 0;
        font-size: 14px;
        opacity: 0.9;
      }
    }
  }
  
  .member-card {
    transition: all 0.3s;
    
    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      transform: translateY(-2px);
    }
  }
  
  :deep(.ant-descriptions-item-label) {
    font-weight: 500;
  }
  
  :deep(.ant-statistic-title) {
    font-size: 14px;
    margin-bottom: 8px;
  }
  
  :deep(.ant-statistic-content) {
    font-size: 24px;
  }
}
</style>

